package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApAuthor;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleClient;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.xml.ws.Response;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-08-07
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Autowired
    ArticleClient articleClient;

    @Autowired
    IApUserService userService;

    @Autowired
    IApUserFollowService followService;

    //App用户登录
    @Override
    public ResponseResult login(LoginDto dto) {
        //参数校验
        if (dto == null || (StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //如果手机号密码不为空，使用手机号和密码登录
        if (!StringUtils.isEmpty(dto.getPassword()) && !StringUtils.isEmpty(dto.getPhone())) {
            //使用手机号查询用户
            LambdaQueryWrapper<ApUser> qw = new LambdaQueryWrapper<>();
            qw.eq(ApUser::getPhone,dto.getPhone());
            ApUser one = this.getOne(qw);
            //获取用户的盐
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            String salt = one.getSalt();
            //拼接进行MD5计算
            String pass = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            //跟数据库中的密码进行对比
            if (pass.equals(one.getPassword())) {
                //使用用户信息生成token
                Map<String, Object> claimMap = new HashMap<>();
                claimMap.put("userId",one.getId());
                String token = AppJwtUtil.getToken(claimMap);
                Map<String, Object> result = new HashMap<>();
                //隐私数据
                one.setPhone(null);
                one.setPassword(null);
                one.setSalt(null);
                result.put("user",one);
                result.put("token",token);
                return ResponseResult.okResult(result);
            }
        }
        //如果设备id不为空，使用游客的身份登录，使用0来生成token
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            Map<String, Object> claimMap = new HashMap<>();
            claimMap.put("userId",0);
            String token = AppJwtUtil.getToken(claimMap);
            Map<String, Object> result = new HashMap<>();
            result.put("token",token);
            return ResponseResult.okResult(result);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }

    //用户关注
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //获取当前登录的用户
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询当前用户信息
        ApUser apUser = userService.getById(user.getUserId());
        //远程查询文章微服务获取作者对应的用户信息
        ResponseResult<ApAuthor> responseResult = articleClient.getAuthorById(dto.getAuthorId());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor author = responseResult.getData();
            if (author != null) {
                //构建ApUserFollow
                ApUserFollow userFollow = new ApUserFollow();
                userFollow.setUserId(user.getUserId());
                userFollow.setUserName(apUser.getName());
                userFollow.setFollowId(author.getUserId());
                userFollow.setFollowName(author.getName());
                userFollow.setLevel(1);
                userFollow.setCreatedTime(new Date());
                //判断操作的方式，如果是关注，保存记录
                LambdaQueryWrapper<ApUserFollow> qw = new LambdaQueryWrapper<>();
                qw.eq(ApUserFollow::getUserId,user.getUserId());
                qw.eq(ApUserFollow::getFollowId,author.getUserId());
                if (dto.getOperation() == 0) {
                    //查询是否有记录
                    int count = followService.count(qw);
                    if (count == 0) {
                        followService.save(userFollow);
                    }
                } else {
                    //如果是取消关注，删除记录
                    followService.remove(qw);
                }
            }
        }
        return ResponseResult.okResult();
    }
}
